package com.czk.shop.mq;

import com.alibaba.fastjson.JSON;
import com.comon.czk.constant.ShopCode;
import com.czk.shop.mapper.TradeOrderMapper;
import com.czk.shop.pojo.TradeOrder;
import com.czk.shop.pojo.TradePay;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;

/**
 * @Author:ChenZhangKun
 * @Date: 2020/11/7 20:58
 */
@Component
@Slf4j
@RocketMQMessageListener(topic = "${mq.pay.topic}",consumerGroup = "${mq.pay.consumer.group.name}",messageModel = MessageModel.BROADCASTING)
public class PaymentListener implements RocketMQListener<MessageExt> {
    @Autowired
    private TradeOrderMapper tradeOrderMapper;
    @Override
    public void onMessage(MessageExt messageExt) {
        // 解析消息内容
        try {
            String body=new String(messageExt.getBody(),"UTF-8");
            TradePay tradePay = JSON.parseObject(body, TradePay.class);
            // 拿到订单对象
            TradeOrder tradeOrder = tradeOrderMapper.selectByPrimaryKey(tradePay.getOrderId());
            // 更改订单支付状态
            tradeOrder.setPayStatus(ShopCode.SHOP_ORDER_PAY_STATUS_IS_PAY.getCode());
            // g更新到数据库
            tradeOrderMapper.updateByPrimaryKey(tradeOrder);
            log.info("已支付");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
}
